package com.openingedu.mba.screen.fragment;

import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.lurencun.android.support.widget.CommonAdapter;
import com.lurencun.android.toolkit.util.ActivitySwitcher;
import com.openingedu.mba.R;
import com.openingedu.mba.common.AppSetting;
import com.openingedu.mba.persist.DbMessage;
import com.openingedu.mba.screen.activity.message.MessageViewActivity;
import com.openingedu.mba.screen.adapter.MessageAdapter;
import com.openingedu.mba.service.MessageService;

/**
 * 
 * 消息
 * 
 * @author unidw
 */
public class FragmentMessage extends SherlockFragment {

	private Context mContext;
	private ListView listView;
	private List<DbMessage> messageList;
	private CommonAdapter<DbMessage> messageAdapter;
	private MessageService messageService;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LinearLayout messageLayout = (LinearLayout)inflater.inflate(R.layout.ft_message, container, false);
		mContext = messageLayout.getContext();
		listView = (ListView) messageLayout.findViewById(R.id.list_container);
		messageAdapter = new MessageAdapter(mContext);
		messageService = new MessageService();
		try {
			messageList = messageService.listMessage(mContext);
			messageAdapter.updateDataCache(messageList);
			listView.setAdapter(messageAdapter);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				try {
					DbMessage message = messageList.get(position);
					message.setRead(true);
					messageService.update(mContext, message);
					messageAdapter.notifyDataSetChanged();
					messageAdapter.updateDataCache(messageList);
					String[] keys = new String[] { AppSetting.MENU_VALUE, AppSetting.MENU_TITLE };
					Object[] vals = new Object[] { message.getContent(), "消息" };
					ActivitySwitcher.switchTo(getSherlockActivity(), MessageViewActivity.class, keys, vals);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		return messageLayout;
	}
}
